package com.hyy.nio.c2;

import com.hyy.nio.c1.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MultiThreadServer {

    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        //1、创建固定数量的 worker 并初始化
        Worker worker = new Worker("worker-01");
        Worker[] workers =new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-"+i);
        }
        AtomicInteger atomicInteger = new AtomicInteger();
        while (true){
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}",sc.getRemoteAddress());
                    //2、关联 selector
                    log.debug("before register...{}",sc.getRemoteAddress());
                    workers[atomicInteger.getAndIncrement()%2].register(sc);
                    log.debug("after register...{}",sc.getRemoteAddress());

                }


            }
        }
    }

    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和selector
        public void register(SocketChannel sc) throws IOException {
            if(!start){
                thread = new Thread(this,name);
                thread.start();
                selector = Selector.open();
                start = true;
            }
            selector.wakeup();
            sc.register(selector,SelectionKey.OP_READ,null);
        }

        @Override
        public void run() {
            while (true){
                try {
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        try {
                            iterator.remove();
                            if(key.isReadable()){
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                log.debug("read...{}",channel.getRemoteAddress());
                                int read = channel.read(buffer);
                                if(read==-1){
                                    log.debug("channel---{}----close", channel);
                                    key.cancel();
                                }else{
                                    buffer.flip();
                                    ByteBufferUtil.debugAll(buffer);
                                }


                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            //客户端断开了，所以将事件取消
                            key.cancel();
                        }


                    }
                } catch (Exception e) {

                }

            }
        }
    }
}
